<?php

function deleteDirectory($dir) {
    if (!file_exists($dir)) return true;
    if (!is_dir($dir)) return unlink($dir);
    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') continue;
        if (!deleteDirectory($dir.DIRECTORY_SEPARATOR.$item)) return false;
    }
    return rmdir($dir);
}

class jwGallery extends BasejwGallery
{
    protected $forceUpdate = false;
    
    public function forceUpdate()
    {
        $this->forceUpdate = true;
    }
    
    public function __toString()
    {
        return $this->getName();
    }
    
    public function doSave( PropelPDO $con )
    {
        if ( $this->isNew() )
        {
            $dirname = md5( time().rand()*10000 );
            $this->setPath( $dirname );
        }
        
        if( $this->forceUpdate )
        {
            if( !$this->isNew() )
            {                
                $c = new Criteria();
                $c->add( jwGalleryPicturePeer::GALLERY_ID, $this->getId() );
                
                if ( $this->colljwGalleryPictures  )
                {
                    $exclude = array();
                    foreach( $this->colljwGalleryPictures as $picObj )
                    {
                        $exclude[] = $picObj->getId();
                    }
                    $c->add( jwGalleryPicturePeer::ID, $exclude, Criteria::NOT_IN );
                }
                $pictures = jwGalleryPicturePeer::doSelect( $c );
                foreach( $pictures as $picture )
                    $picture->delete();                
            }
        }
        
        parent::doSave( $con );
    }
    
    public function delete(PropelPDO $con = null)
    {        
        parent::delete( $con );

        if ( $this->isDeleted() )
        {               
            $path = $this->getPath();
            $rootDir = sfConfig::get( 'sf_root_dir');
            $baseDir = $rootDir.DIRECTORY_SEPARATOR.'galleries'.DIRECTORY_SEPARATOR.$path;
            deleteDirectory( $baseDir );
        }
    }
}
